package com.hr.huangzhk.interceptor;

import com.hr.huangzhk.domain.User;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpSession;
import java.util.Map;


/**
 * Created by huangzhk on 2016/10/20.
 */

@Component
public class WebSocketInterceptor implements HandshakeInterceptor {

  @Override
  public boolean beforeHandshake(ServerHttpRequest serverHttpRequest,
      ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler,
      Map<String, Object> map) throws Exception {
    ServletServerHttpRequest request = (ServletServerHttpRequest) serverHttpRequest;
    HttpSession session = request.getServletRequest().getSession();
    if (session != null) {
      User user = (User) session.getAttribute("user");
      map.put("userId", user.getId());
    }
    return true;
  }

  @Override
  public void afterHandshake(ServerHttpRequest serverHttpRequest,
      ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) {

  }
}
